import { defineStore } from 'pinia'
import { displayByName } from '@/cesiumTools/effectController'
export const useLineData = defineStore('lineData', {
  state: () => {
    return {
      lineData: [],
      // 全局共享viewer，注意标记为markRaw
      viewer: null,
      tileset: null,
      //管理面板的开关
      PanelDisplay: true,
    }
  },
  getters: {
    // 获取全部信息
    allData() {
      return this.lineData
    },
    Viewer() {
      return this.viewer
    },
    Tile() {
      return this.tileset
    },
  },
  actions: {
    setData(data) {
      return new Promise((resolve, reject) => {
        this.lineData = data.length ? data : []
        resolve(data)
      })
    },
    setViewer(viewer) {
      return new Promise((resolve, reject) => {
        this.viewer = viewer
        resolve(viewer)
      })
    },
    setTileset(tileset) {
      return new Promise((resolve, reject) => {
        this.tileset = tileset
        resolve(tileset)
      })
    },
    // 全选，控制所有站点，站线

    // 全局管理路线显隐
    displayLine(lineNames, isShow) {
      if (Array.isArray(lineNames) && this.lineData.length && !this.disable) {
        const stationNames = []
        // 控制state数据
        this.lineData.forEach((item) => {
          const { stationsList, name } = item
          if (lineNames.includes(name)) {
            item.checked = isShow
            stationsList.forEach((station) => {
              stationNames.push(station.name)
            })
          }
        })
        // 控制地图元素
        displayByName(lineNames, stationNames, isShow)
      }
    },
    // 设置是否开启全局管理
    disableController(val) {
      this.disable = val
    },
  },
})

// 由于lineData的state是异步的，所以需要监听action来获取数据
export const watchLineData = (actionName = 'setData') => {
    return new Promise((resolve, reject) => {
        useLineData().$onAction(({ name, store, args, after, onError }) => {
            // console.log(name)
            // console.log(actionName)
            if (name === actionName) {
                after((res) => {
                    if (res) {
                        // console.log(111)
                        resolve(res)
                    }
                })

                onError((e) => {
                    console.log(222)
                    reject(e)
                })
            }
        })
    })
}

export const useMeasureData = defineStore('measureData', {
  state: () => {
    return {
      measureData: [],
    }
  },

  actions: {
    setData(data) {
      return new Promise((resolve, reject) => {
        this.measureData = data.length ? data : []
        resolve(data)
      })
    },
    clearData() {
      return new Promise((resolve, reject) => {
        const data = this.measureData.map((item) => {
          item.length && item.forEach((n) => (n.measures.length = 0))
          return item
        })
        this.measureData = data
        resolve(data)
      })
    },
  },
})
